import { Prisma } from '@prisma/client';
import prisma from '@/server/lib/prisma';
import { PostSchema } from '@/server/lib/zodSchema';

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    PostSchema.parse(body); // 校验参数

    // 判断岗位编码和名称是否已存在
    const isPostCode = await prisma.sys_post.findFirst({
      where: {
        postCode: body.postCode
      }
    })
    if (isPostCode) {
      return {
        code: 400,
        msg: '岗位编码已存在',
      }
    }

    const isPostName = await prisma.sys_post.findFirst({
      where: {
        postName: body.postName
      }
    })
    if (isPostName) {
      return {
        code: 400,
        msg: '岗位名称已存在',
      }
    }

    // 参数
    const data: Prisma.sys_postCreateInput = {
      postCode: body.postCode,
      postName: body.postName,
      postSort: Number(body.postSort),
      status: body.status,
      remark: body.remark,
    }
    const result = await prisma.sys_post.create({
      data,
    });
    return {
      code: 200,
      data: result,
      msg: '创建成功'
    }
  } catch (error: any) {
    const err = JSON.parse(error)
    return {
      code: 400,
      msg: err[0].message || '未知错误',
    }
  } finally {
    await prisma.$disconnect(); // 关闭连接
  }
})
